<template>
	<view class="user-info">
		<view class="desc">
			<text>个人信息</text>
		</view>
		<view class="info-list">
			<view class="info-item">
				<button v-if="hasLogin" open-type="chooseAvatar" class="info-btn" @click="uploadAvatarImg"
					@chooseavatar="bindchooseavatar">
					<view class="label"><text>头像</text></view>
					<view class="right-content">
						<view class="user-img-view">
							<image :src="userImgUrl"></image>
						</view>
						<uni-icons type="right" size="18" class="arrow-icon"></uni-icons>
					</view>
				</button>
				<button v-if="!hasLogin" class="info-btn" @click="goLogin">
					<view class="label"><text>头像</text></view>
					<view class="right-content">
						<view class="user-img-view">
							<image :src="userImgUrl"></image>
						</view>
						<uni-icons type="right" size="18" class="arrow-icon"></uni-icons>
					</view>
				</button>
			</view>

			<!-- 昵称项 - 横向布局，样式与头像项统一 -->
			<view class="info-item">
				<view class="info-btn">
					<view class="label"><text>昵称</text></view>
					<view class="right-content">
						<view class="content-wrapper">
							<input @blur="setNickname" type="nickname" class="nickname-input" :value="nickname" />
						</view>
						<uni-icons type="right" size="18" class="arrow-icon"></uni-icons>
					</view>
				</view>
			</view>

		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from "vue";

	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js';

	import {
		convertCloudUrl
	} from "@/utils/common.js";

	// 响应式变量
	const isPC = ref(false);
	const userImgUrl = ref("");
	const nickname = ref("");

	// 计算属性
	const hasLogin = computed(() => store.hasLogin);
	const userInfo = computed(() => store.userInfo);
	const avatarFile = store.userInfo.avatar_file;

	nickname.value = userInfo.value.nickname;

	if (avatarFile === undefined) {
		userImgUrl.value = "/static/defAvatar.png";
	} else {
		userImgUrl.value = convertCloudUrl(avatarFile.url);
	}

	/**
	 * 组件挂载完成后执行代码
	 */
	onMounted(() => {
		// 初始化逻辑
		const platform = uni.getSystemInfoSync().platform;
		isPC.value = !['ios', 'android'].includes(platform) || platform === 'harmonyos';
	});

	/**
	 * 跳转登录页面
	 */
	const goLogin = () => {
		return uni.navigateTo({
			// #ifdef MP-WEIXIN
			url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
			// #endif
			// #ifndef MP-WEIXIN
			url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
			// #endif
		})
	}

	/**
	 * 微信小程序的头像选择功能
	 */
	const bindchooseavatar = async (res) => {
		let avatarUrl = res.detail.avatarUrl
		let avatar_file = {
			extname: avatarUrl.split('.')[avatarUrl.split('.').length - 1],
			name: '',
			url: ''
		}
		//上传到服务器
		let cloudPath = userInfo.value._id + '' + Date.now() + '.' + avatar_file.extname
		avatar_file.name = cloudPath;

		try {
			uni.showLoading({
				title: "更新中",
				mask: true
			});
			let {
				fileID
			} = await uniCloud.uploadFile({
				filePath: avatarUrl,
				cloudPath,
				fileType: "image"
			});
			avatar_file.url = fileID
			uni.hideLoading()
		} catch (e) {
			console.error(e);
		}
		console.log('avatar_file', avatar_file);
		mutations.updateUserInfo({
			avatar_file
		});
		// 刷新数据
		userImgUrl.value = convertCloudUrl(avatar_file.url);
	}

	/**
	 * 上传图像
	 */
	const uploadAvatarImg = (res) => {
		if (!hasLogin) {
			return uni.navigateTo({
				// #ifdef MP-WEIXIN
				url: '/uni_modules/uni-id-pages/pages/login/login-withoutpwd'
				// #endif
				// #ifndef MP-WEIXIN
				url: '/uni_modules/uni-id-pages/pages/login/login-withpwd'
				// #endif
			})
		}
		// #ifdef MP-WEIXIN
		return false // 微信小程序走 bindchooseavatar方法
		// #endif
		// 图像裁剪参数
		const crop = {
			quality: 100,
			width: 600,
			height: 600,
			resize: true
		};
		uni.chooseImage({
			count: 1,
			crop,
			success: async (res) => {
				let tempFile = res.tempFiles[0];
				let filePath = res.tempFilePaths[0];
				let avatar_file = {
					// #ifdef H5
					extname: tempFile.name.split('.')[tempFile.name.split('.').length - 1],
					// #endif
					// #ifndef H5
					extname: tempFile.path.split('.')[tempFile.path.split('.').length - 1]
					// #endif
				}
				let cloudPath = userInfo.value._id + '' + Date.now() + '.' + avatar_file.extname;
				avatar_file.name = cloudPath;

				//非app端剪裁头像，app端用内置的原生裁剪
				// #ifdef H5
				if (!isPC.value) {
					filePath = await new Promise((callback) => {
						uni.navigateTo({
							url: '/uni_modules/uni-id-pages/pages/userinfo/cropImage/cropImage?path=' +
								filePath + `&options=${JSON.stringify(crop)}`,
							animationType: "fade-in",
							events: {
								success: url => {
									callback(url)
								}
							},
							complete(e) {
								console.log(e);
							}
						});
					})
				}
				// #endif

				uni.showLoading({
					title: "更新中",
					mask: true
				});

				let {
					fileID
				} = await uniCloud.uploadFile({
					filePath,
					cloudPath,
					fileType: "image"
				});

				uni.hideLoading();

				// 更新用户
				avatar_file.url = fileID;
				mutations.updateUserInfo({
					avatar_file
				});

				// 刷新数据
				userImgUrl.value = convertCloudUrl(avatar_file.url);

			}
		})
	}

	/**
	 * 设置昵称
	 */
	const setNickname = (nickname) => {
		nickname = nickname.detail.value;
		if (nickname) {
			mutations.updateUserInfo({
				nickname
			})
		}
	}
</script>

<style lang="scss" scoped>
	.user-info {
		min-height: 100vh;
		background-color: #FAFAFA;
		padding: 0 60rpx;

		.desc {
			font-size: 60rpx;
			font-weight: 500;
			padding: 90rpx 0;
		}

		.info-list {
			.info-item {
				display: flex;
				padding: 40rpx 0;
				align-items: center;
				border-bottom: 1px solid #eee;

				// 统一按钮样式，同时应用于头像和昵称项
				.info-btn {
					display: flex;
					justify-content: space-between;
					align-items: center;
					width: 100%;
					background: transparent;
					padding: 0;
					margin: 0;
					border: none;
					outline: none;
					text-align: left;

					&::after {
						border: none;
					}

					.label {
						flex: 0 0 auto;
						font-size: 32rpx;
						color: #333;
						margin-right: 20rpx;
					}

					.right-content {
						display: flex;
						align-items: center;
						flex: 1;
						justify-content: flex-end;
						gap: 20rpx;
					}

					.content-wrapper {
						// 内容容器，与头像容器保持一致的布局行为
						display: flex;
						align-items: center;
						justify-content: flex-end;
						flex: 1;
					}

					.user-img-view {
						display: flex;
						align-items: center;
						justify-content: center;

						image {
							width: 108rpx;
							height: 108rpx;
							border-radius: 50%;
							object-fit: cover;
						}
					}

					.nickname-input {
						border: none;
						// 昵称文本样式，与头像区域视觉对齐
						font-size: 32rpx;
						color: #666;
						text-align: right;
					}

					.arrow-icon {
						flex: 0 0 auto;
						color: #ccc;
					}
				}

			}

		}
	}
</style>